package com.example.demo_text;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/SubmitCommentServlet")
public class SubmitCommentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        
        try {
            // Get parameters
            int ansId = Integer.parseInt(request.getParameter("answer_id"));
            String commentContent = request.getParameter("comment_content");
            String courseId = request.getParameter("course_id");
            
            // Add comment to database
            boolean success = CommentDAO.addComment(ansId, commentContent);
            
            if (success) {
                // Redirect back to discussions with success message
                response.sendRedirect("class_space.jsp?course_id=" + courseId + "&tab=discussions");
            } else {
                // Redirect with error message
                response.sendRedirect("class_space.jsp?course_id=" + courseId + "&tab=discussions&error=Failed to add comment");
            }
        } catch (Exception e) {
            e.printStackTrace();
            String courseId = request.getParameter("course_id");
            if (courseId != null && !courseId.isEmpty()) {
                response.sendRedirect("class_space.jsp?course_id=" + courseId + "&tab=discussions&error=" + e.getMessage());
            } else {
                response.sendRedirect("error.jsp?message=" + e.getMessage());
            }
        }
    }
} 